/*
 *  Copyright 2010 sonrisa.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.zh.jbet.core.dao;

import com.zh.jbet.core.entity.Bet;
import com.zh.jbet.core.entity.BetContextEntity;
import java.text.MessageFormat;
import javax.persistence.Query;

/**
 *
 * @author sonrisa
 */
public class BetContextDao extends BaseJpaDao<BetContextEntity> {
    /*
     * update 	adatszolgaltatas_peldany p
    set	p.version =
    (select (t1.s + t2.s)
    from (select sum(ds.version) as s from adatszolgaltatas_definicio ds) t1, (select sum(dt.version) as s from adatszolgaltatas_definicio dt) t2)

     */

    private static final String UPDATE_CONTEXT = "UPDATE BetContextEntity bc SET bc.point = SELECT ";
    private static final MessageFormat FROM_CONTEXT = new MessageFormat("(SELECT SUM({0}.point) as {1} "
            + "FROM {2} {0} WHERE {0}.playerGameId = ?1 AND {0}.gameId = ?2) {3}, ");

    public void updateContext(Bet bet) {

        //Long parentId = bet.g
        /*
        StringBuffer select = new StringBuffer();
        StringBuffer from = new StringBuffer();
        appendSelectAndFrom(select, from, clazz, 0);
        if (betClass != null) {
            //for (int i=0; i< betClasses.length; i++) {
            appendSelectAndFrom(select, from, betClass, 1);
            //}
        }
        select.delete(select.length() - 3, select.length());
        from.delete(from.length() - 2, from.length());
        String finalSql = UPDATE_CONTEXT + "(" + select.toString() + ") FROM " + from.toString();
        Query q = entityManager.createQuery(finalSql);
        q.setParameter(1, playerGameId);
        q.setParameter(2, gameId);
        q.executeUpdate();
         * 
         */
    }
    private static final String SUMF = "s";

    private void appendSelectAndFrom(StringBuffer select, StringBuffer from, Class<? extends Bet> betClass, int idx) {
        String tableName = "t" + idx;
        String summTableName = "s" + idx;
        select.append(tableName + "." + SUMF + " + ");
        FROM_CONTEXT.format(new Object[]{summTableName, SUMF, betClass.getSimpleName(), tableName}, from, null);
    }
}
